//  <(((*> <(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*>
//
//          EXIF ReName
//          Copyright (C) 2007 - 2021 Ingemar Ceicer
//          https://gitlab.com/posktomten/exifrename2
//          ic_0002 (at) ceicer (dot) com
//
//   This program is free software: you can redistribute it and/or modify
//   it under the terms of the GNU General Public License version 3
//   as published by the Free Software Foundation.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
// <(((*> <(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*>

#include "mainwindow.h"
#include "ui_tabwidget.h"
#include "ui_mainwindow.h"
void MainWindow::openCopy()
{
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, DISPLAY_NAME,
                       EXECUTABLE_NAME);
    settings.setIniCodec("UTF-8");
    settings.beginGroup("Extensions");
    QStringList selectedfilters = settings.value("selectedfilters").toStringList();
    selectedfilters.sort(Qt::CaseInsensitive);
    settings.endGroup();
    QDir dir(QDir::home());
    QString home = QDir::toNativeSeparators(dir.absolutePath());
    settings.beginGroup("Path");
    QString openpath = settings.value("openpath", home).toString();
    settings.endGroup();
    QFileDialog * dialog = new QFileDialog(this);
    dialog->resize(900, 600);
    dialog->setViewMode(QFileDialog::Detail);
    dialog->setFileMode(QFileDialog::ExistingFiles);
    dialog->setWindowTitle(tr("Select file or files to be copied and renamed"));
    settings.beginGroup("Tools");
    dialog->setOption(QFileDialog::DontUseNativeDialog, !settings.value("usenativedialog").toBool());
    bool useopenpath = settings.value("useopenpath", false).toBool();
    settings.endGroup();
    settings.beginGroup("Extensions");
    QString selectednamefilter = settings.value("selectednamefilter", "tomt").toString();
    settings.endGroup();

    if(useopenpath) {
        if(!TabWidget::pathExist(openpath)) {
            dialog->setDirectory(home);
        } else if(openpath.isEmpty()) {
            dialog->setDirectory(home);
        } else {
            dialog->setDirectory(openpath);
        }
    } else {
        dialog->setDirectory(home);
    }

    QStringList fileNames;

    if(selectednamefilter != "tomt") {
        dialog->setNameFilters(QStringList() << selectednamefilter << selectedfilters);
    } else {
        dialog->setNameFilters(selectedfilters);
    }

    if(dialog->exec()) {
        fileNames = dialog->selectedFiles();
        copy(fileNames);
        QDir dir = dialog->directory();
        openpath = dir.path();
        settings.beginGroup("Path");
        settings.setValue("openpath", openpath);
        settings.endGroup();
        settings.beginGroup("Extensions");
        settings.setValue("selectednamefilter", dialog->selectedNameFilter());
        settings.endGroup();
    }
}
void MainWindow::copy(QList<QUrl> urls)
{
    QStringList localurls;

    foreach(QUrl u, urls) {
        localurls << QString(u.toLocalFile());
    }

    copy(localurls);
}

void MainWindow::copy(QStringList urls)
{
    QDir dir(QDir::home());
    QString home = QDir::toNativeSeparators(dir.absolutePath());
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, DISPLAY_NAME,
                       EXECUTABLE_NAME);
    settings.setIniCodec("UTF-8");
    settings.beginGroup("Path");
    QString defaultcopypath = settings.value("defaultcopypath", home).toString();
    QString copypath = settings.value("copypath", home).toString();
    settings.endGroup();
    settings.beginGroup("PathPattern");
    bool extensioninfoldernamepattern = settings.value("extensioninfoldernamepattern", false).toBool();
    bool yearsinfoldernamepattern = settings.value("yearsinfoldernamepattern", false).toBool();
    QString folderpattern = settings.value("folderpattern", "-").toString();
    settings.endGroup();
    settings.beginGroup("Extensions");
    QStringList selectedextensions = settings.value("selectedextensions").toStringList();
    settings.endGroup();
    settings.beginGroup("Tools");
    bool alwayscopytodefaultlocation = settings.value("alwayscopytodefaultlocation", false).toBool();
    bool checkredtext = settings.value("checkredtext", false).toBool();
    settings.endGroup();
    QStringList filestorename;

    if(alwayscopytodefaultlocation && !defaultcopypath.isEmpty()) {
        copypath = defaultcopypath;
    } else if(!alwayscopytodefaultlocation) {
        QFileDialog * dialog = new QFileDialog(this);
        /* */
        settings.beginGroup("Tools");
        dialog->setOption(QFileDialog::DontUseNativeDialog, !settings.value("usenativedialog").toBool());
        settings.endGroup();
        /* */
        dialog->resize(900, 600);
        dialog->setFileMode(QFileDialog::DirectoryOnly);

        if(!TabWidget::pathExist(copypath)) {
            dialog->setDirectory(home);
        } else if(copypath.isEmpty()) {
            dialog->setDirectory(home);
        } else {
            dialog->setDirectory(copypath);
        }

        if(dialog->exec()) {
            dialog->resize(320, 240);
            QDir dir = dialog->directory();
            copypath = dir.path();
            settings.beginGroup("Path");
            settings.setValue("copypath", copypath);
            settings.endGroup();
        } else {
            return;
        }
    }

    Exif exif;
    int antalfiles = urls.count();

    if(antalfiles == 1) {
        ui->textBrowserMain->append(tr("Trying to copy") + " " + QString::number(antalfiles) + " " + tr("file"));
    } else {
        ui->textBrowserMain->append(tr("Trying to copy") + " " + QString::number(antalfiles) + " " + tr("files"));
    }

    foreach(QString s, urls) {
        QFileInfo fi(s);

        if(!selectedextensions.contains(fi.suffix(), Qt::CaseInsensitive)) {
            if(checkredtext) {
                ui->textBrowserMain->setTextColor(QColor("red"));
                ui->textBrowserMain->append(tr("Incorrect file name extension.") + " \"" + QDir::toNativeSeparators(s) + "\"");
                ui->textBrowserMain->setTextColor(QColor("black"));
            } else {
                ui->textBrowserMain->append(tr("Incorrect file name extension.") + " \"" + QDir::toNativeSeparators(s) + "\"");
            }

            continue;
        }

        QString tmp = copypath;
        QFileInfo ficopypath(copypath);

        if(!ficopypath.isWritable()) {
//            QMessageBox::critical(this, DISPLAY_NAME " " VERSION,
//                                  tr("Unable to copy to") + "\n" + QDir::toNativeSeparators(copypath) + "\n" + tr("Check your file permissions."));
            return;
        }

        char *hittat = new char[20];
        QString *info = new QString;
        bool b = exif.getExif(s, hittat, info);
        QString testfile;
        testfile = QString::fromLatin1(hittat);
        QRegExp rx("[0-9]{4}x[0-9]{2}x[0-9]{2}x[0-9]{2}x[0-9]{2}x[0-9]{2}");

        if(!rx.exactMatch(testfile)) {
            if(checkredtext) {
                ui->textBrowserMain->setTextColor(QColor("red"));
                ui->textBrowserMain->append(tr("No EXIF data found in") + " \"" + QDir::toNativeSeparators(s) + "\"");
                ui->textBrowserMain->setTextColor(QColor("black"));
            } else {
                ui->textBrowserMain->append(tr("No EXIF data found in") + " \"" + QDir::toNativeSeparators(s) + "\"");
            }

            b = false;
            ui->textBrowserMain->append("");
        }

        if(b) {
            QString foldername;
            QString folderyear;
            foldername = QString(QString::fromLatin1(hittat));
            foldername = foldername.mid(0, 4) + folderpattern + foldername.mid(5, 2) + folderpattern + foldername.mid(8, 2);

            if(yearsinfoldernamepattern) {
                folderyear = foldername.mid(0, 4);
                copypath.append("/" + folderyear);
                dir.mkpath(copypath);
            }

            copypath.append("/" + foldername);
            dir.mkpath(copypath);
        } else {
            continue;
        }

        if(extensioninfoldernamepattern) {
            QString suffix = fi.suffix();
            suffix = suffix.toLower();
            copypath.append("/" + suffix);
            dir.mkpath(copypath);
        }

        if(fi.exists(copypath + "/" + fi.fileName())) {
            if(checkredtext) {
                ui->textBrowserMain->setTextColor(QColor("red"));

                if(antalfiles == 1) {
                    ui->textBrowserMain->append(tr("The file cannot overwrite itself. You are trying to copy") + " " + QString::number(antalfiles) + " " + tr("file to itself."));
                } else {
                    ui->textBrowserMain->append(tr("The file cannot overwrite itself. You are trying to copy") + " " + QString::number(antalfiles) + " " + tr("files to itself."));
                }

                ui->textBrowserMain->setTextColor(QColor("black"));
            } else {
                if(antalfiles == 1) {
                    ui->textBrowserMain->append(tr("The file cannot overwrite itself. You are trying to copy") + " " + QString::number(antalfiles) + " " + tr("file to itself."));
                } else {
                    ui->textBrowserMain->append(tr("The file cannot overwrite itself. You are trying to copy") + " " + QString::number(antalfiles) + " " + tr("files to itself."));
                }
            }

            ui->textBrowserMain->append("");
            return;
        }

        if(!QFile::copy(s, copypath + "/" + fi.fileName())) {
            if(checkredtext) {
                ui->textBrowserMain->setTextColor(QColor("red"));
                ui->textBrowserMain->append(tr("Prohibited from copying to:") + " \"" + QDir::toNativeSeparators(copypath) + "\" " + tr("Check your file permissions."));
                ui->textBrowserMain->setTextColor(QColor("black"));
            } else {
                ui->textBrowserMain->append(tr("Prohibited from copying to:") + " \"" + QDir::toNativeSeparators(copypath) + "\" " + tr("Check your file permissions."));
            }

//            QMessageBox::critical(this, DISPLAY_NAME " " VERSION,
//                                  tr("Unable to write file") + "\n" + QDir::toNativeSeparators(copypath + "/" + fi.fileName()) + "\n" + tr("Check your file permissions."));
//            return;
        } else {
            filestorename << copypath + "/" + fi.fileName();
            copypath = tmp;
        }
    }

    if(filestorename.isEmpty()) {
        ui->textBrowserMain->append(tr("No file was copied"));
    } else {
        int antalfiles = filestorename.count();

        if(antalfiles == 1) {
            ui->textBrowserMain->append(QString::number(antalfiles) + " " + tr("file was copied"));
        } else {
            ui->textBrowserMain->append(QString::number(antalfiles) + " " + tr("files was copied"));
        }

        findExif(filestorename);
    }
}
